package szk.exam.filter;

import szk.exam.pojo.Student;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        Student loginInfo = (Student) req.getSession().getAttribute("loginInfo");
        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        if (loginInfo==null && !requestURI.equalsIgnoreCase(req.getContextPath()+"/Login.jsp") &&
                 !requestURI.equalsIgnoreCase(req.getContextPath()+"/stu/login")) {
            //没有登录
            resp.sendRedirect(req.getContextPath()+"/Login.jsp");
        }
        //已登录 放行
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}
